const Usecase = require('../../shared/usecase/Usecase')
const UserStatus = require('../../domain/user/UserStatus')
const { UserNotFoundError } = require('../../domain/user/error')

class EnableUser extends Usecase {
  constructor({ userRepo, database, currentUser }) {
    super(['EnabledUser'])
    this.userRepo = userRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }

  async execute(data) {
    const { EnabledUser } = this.eventMap
    const user = await this.userRepo.findById(data)
    if (!user) throw new UserNotFoundError(data)
    const transaction = await this.sequelize.transaction()
    try {
      user.status = UserStatus.ENABLE
      await this.userRepo.update(user, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
      this.emit(EnabledUser, user)
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = EnableUser
